/****** Object:  Stored Procedure dbo.CGO_PaymentGetList    Script Date: Thursday, March 24, 2011 ******/
IF EXISTS ( SELECT  *
            FROM    dbo.sysobjects
            WHERE   id = OBJECT_ID(N'dbo.CGO_PaymentGetList')
                    AND OBJECTPROPERTY(id, N'IsProcedure') = 1 ) 
  DROP PROCEDURE dbo.CGO_PaymentGetList
GO

/* -------------------------------------------------------------------------------------
/   PaymentGetList 
/  ------------------------------------------------------------------------------------- */
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE dbo.CGO_PaymentGetList
  @PortalID INT ,
  @UserID INT ,
  @EnrollmentID INT,
  @StatusID INT ,
  @GetCount BIT = 0,
  @PageSize INT = 10,
  @CurrentPage INT = 1
AS 
  DECLARE @TotalRowCount INT
  SET @TotalRowCount = 0
  
  IF @GetCount IS NULL
  BEGIN
  	SET @GetCount = 0
  END
  IF @PageSize IS NULL
  BEGIN
	  SET @PageSize = 10
  END
  IF @CurrentPage IS NULL
  BEGIN
	  SET @CurrentPage = 1
  END
  
  IF @GetCount = 1
  BEGIN
    SELECT  @TotalRowCount = COUNT(*)
    FROM    dbo.CGO_Payment
    WHERE   PortalID = @PortalID
            AND ( @UserID = 0
                  OR UserID = @UserID
                )
            AND ( @EnrollmentID = 0
                  OR EnrollmentID = @EnrollmentID
                )
            AND ( @StatusID = 0
                  OR StatusID = @StatusID
                )
  END
    
  SET ROWCOUNT @PageSize
  
  SELECT  @TotalRowCount AS TotalRowCount ,
          T.*
  FROM    ( SELECT  ROW_NUMBER() OVER ( ORDER BY LastUpdateDate DESC, CreatedDate DESC ) AS RANK ,
                    PaymentID ,
                    PortalID ,
                    M.UserID ,
                    U.Username ,
                    Amount ,
                    M.StatusID ,
                    S.StatusDesc AS PaymentStatus ,
                    EnrollmentID ,
                    CreatedDate ,
                    LastUpdateDate
            FROM    dbo.CGO_Payment M
                    LEFT JOIN dbo.Users U ON M.UserID = U.UserID
                    LEFT JOIN dbo.CGO_PaymentStatus S ON M.StatusID = S.StatusID
            WHERE   PortalID = @PortalID
                    AND ( @UserID = 0
                          OR M.UserID = @UserID
                        )
                    AND ( @EnrollmentID = 0
                          OR EnrollmentID = @EnrollmentID
                        )
                    AND ( @StatusID = 0
                          OR M.StatusID = @StatusID
                        )
          ) T
  WHERE   T.[RANK] > ( @CurrentPage - 1 ) * @PageSize
  
  
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
